package com.amado.course40Reflect.homework;

import java.lang.reflect.Field;

public class PropertiesCopyUtil {
	public static void copy(Object src, Object dest) {
		Field[] srcFields = src.getClass().getDeclaredFields();
		Field[] destFields = dest.getClass().getDeclaredFields();
		for (Field srcField : srcFields) {
			Field destField = getProperties(srcField,destFields);
			if(destField!=null){
				srcField.setAccessible(true);
				destField.setAccessible(true);
				try {
					//copy
					destField.set(dest, srcField.get(src));
				} catch (IllegalArgumentException | IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		copySuperClass(src,dest);
	}
	public static void copySuperClass(Object src, Object dest) {
		Field[] srcFields = src.getClass().getSuperclass().getDeclaredFields();
		Field[] destFields = dest.getClass().getSuperclass().getDeclaredFields();
		for (Field srcField : srcFields) {
			Field destField = getProperties(srcField,destFields);
			if(destField!=null){
				srcField.setAccessible(true);
				destField.setAccessible(true);
				try {
					destField.set(dest, srcField.get(src));
				} catch (IllegalArgumentException | IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public static  Field getProperties(Field field ,Field[] destFields) {
		for (Field destField : destFields) {
			if(field.getName().equals(destField.getName()) && field.getType().equals(destField.getType())){
				return destField;
			}
		}
		return null;
	}

	public static void main(String[] args) {
		reflect();
		reflect();
	}
	
	public static void noReflect () {
		Teacher teacher = new Teacher();
		Student student = new Student("addr","nage",11,"telphone");
		teacher.setAddr(student.getAddr());
		teacher.setAge(student.getAge());
		teacher.setName(student.getName());
		teacher.setPhone(student.getPhone());
		
		System.out.println("之后 ："+teacher.getAddr());
		System.out.println("之后 ："+teacher.getName());
		System.out.println("之后 ："+teacher.getPhone());
	}
	
	public static void reflect() {
		Teacher teacher = new Teacher();
		System.out.println("之前 ："+teacher.getAddr());
		copy(new Student("addr","nage",11,"telphone"), teacher);
		System.out.println("之后 ："+teacher.getAddr());
		System.out.println("之后 ："+teacher.getName());
		System.out.println("之后 ："+teacher.getPhone());
	}
}
